package com.imooc.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;

public class CuratorTests {
    public static void main(String[] args) throws Exception {
        String connectionString = "127.0.0.1:2181";
        ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(connectionString, retry);
        client.start();
        String path = "/imooc-curator";
        String data = "Hello, Curator!";
        String data2 = "Hello, Curator! Updated";
        // 使用NodeCache监听节点数据变化
        NodeCache nodeCache = new NodeCache(client, path);
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                byte[] newData = nodeCache.getCurrentData() != null ? nodeCache.getCurrentData().getData() : null;
                System.out.println("Node data changed: " + (newData != null ? new String(newData) : null));
            }
        });
        nodeCache.start();

        client.create().withMode(CreateMode.PERSISTENT).forPath(path, data.getBytes());
        Thread.sleep(1000); // 等待节点创建和监听器初始化
        client.setData().forPath(path, data2.getBytes());
        Thread.sleep(1000); // 等待监听器回调
        client.delete().forPath(path);
        nodeCache.close();
        Thread.sleep(2000); // 等待2秒，观察连接状态变化
    }
}
